import {
  selectPeriodTypeByTypeCode,
  selectPmGroupByPmPeriodCode,
  startPmForm
} from '@/api/evalutaion'
import {CCard} from '@/components/card'
import {PMContent, PMLayout, PMNav} from '@/components/others/layout'
import {CnMediumSpan} from '@/components/text'
import {useRouteQuery} from '@/hooks/pageRedirect'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import deepClone from '@/libs/deepClone'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {InitiateAssessmentPageQuery} from '@/libs/pageRedirect'
import {getSession} from '@/libs/sessionStorage'
import dayjs, {Dayjs} from 'dayjs'
import { defineComponent, reactive, computed, watch, onMounted } from 'vue'
const {message} = ant_design_vue
/**发起考核 */
export default defineComponent({
  name: 'initiatedAssessment',
  setup(props, ctx) {
    const {router} = useGlobalAPI()
    const {getQueryData} = useRouteQuery()

    let queryData = getQueryData<InitiateAssessmentPageQuery>()

    const defaultPmGroupId = queryData?.pmGroupId ? Number(queryData.pmGroupId) : undefined

    const defaultPmPeriodCode = queryData?.pmPeriodCode

    const defaultPmGroupName = queryData?.pmGroupName

    /**页面状态 */
    let state = reactive<{
      beSelectedPmGroupIds: number[]
      currentPmPeriod: Dict.Item<'008', string> | undefined
      timePeriod: Dayjs | number | undefined
      pmFormName: string | undefined
    }>({
      beSelectedPmGroupIds: defaultPmGroupId ? [defaultPmGroupId] : [],
      currentPmPeriod: undefined,
      timePeriod: undefined,
      pmFormName: ''
    })

    /**考评组筛选弹窗状态 */
    let selectEvalutaionModal = reactive<{
      visible: boolean
      evalutaionDatas: Evaluation.PmGroupByPmPeriodCode[]
      pmGroupName: string
      pmPeriodList: Dict.Item<'008', string>[]
    }>({
      visible: false,
      evalutaionDatas: [],
      pmGroupName: '',
      pmPeriodList: []
    })

    /**已选择的考评组 */
    const beSelectedEvalutaions = computed(() =>
      selectEvalutaionModal.evalutaionDatas.filter(
        item => state.beSelectedPmGroupIds.indexOf(item.pmGroupId) !== -1
      )
    )

    /**自动生成考评组名称 */
    const pmFormName = computed(() => {
      if (!state.currentPmPeriod) return undefined

      if (state.currentPmPeriod.dictCode === '0029') return ''

      if (state.timePeriod === undefined) return undefined

      let name: string = dayjs().format('YYYY') + '年'

      const suffix = '绩效考核'

      function comboxName(value: string, newName?: string) {
        return (newName ? newName : name) + value + suffix
      }

      if (typeof state.timePeriod === 'number') {
        return comboxName(state.timePeriod === 1 ? '上半年' : '下半年')
      } else {
        switch (state.currentPmPeriod.dictCode) {
          case '0025':
            return comboxName(
              state.timePeriod.format('M') + '月',
              state.timePeriod.format('YYYY') + '年'
            )
          case '0026':
            switch (state.timePeriod.format('M')) {
              case '0':
                return comboxName('第一季度', state.timePeriod.format('YYYY') + '年')
              case '3':
                return comboxName('第二季度', state.timePeriod.format('YYYY') + '年')
              case '6':
                return comboxName('第三季度', state.timePeriod.format('YYYY') + '年')
              case '9':
                return comboxName('第四季度', state.timePeriod.format('YYYY') + '年')
              default:
                return comboxName('未知', state.timePeriod.format('YYYY') + '年')
            }
            break
          case '0028':
            name = state.timePeriod.format('YYYY') + '年'
            return comboxName('')
          default:
            return comboxName(
              state.timePeriod.format('M') + '月',
              state.timePeriod.format('YYYY') + '年'
            )
        }
      }
    })

    const filterEvalutaionDatas = computed(() =>
      selectEvalutaionModal.evalutaionDatas.filter(
        item => item.pmGroupName.indexOf(selectEvalutaionModal.pmGroupName) !== -1
      )
    )

    watch(
      () => beSelectedEvalutaions.value,
      n => {
        console.log(n)
      },
      {
        immediate: true
      }
    )

    watch(
      () => state.currentPmPeriod,
      (n, o) => {
        if (o !== undefined) state.beSelectedPmGroupIds = []
        console.log(state.beSelectedPmGroupIds)

        state.timePeriod = undefined
        getEvalutaionModalData()
      }
    )

    watch(
      () => state.timePeriod,
      n => {
        console.log(n)
      }
    )

    watch(
      () => pmFormName.value,
      n => {
        state.pmFormName = n
      }
    )

    /**获取考评组弹窗状态 */
    function getEvalutaionModalData() {
      if (!state.currentPmPeriod) return
      selectPmGroupByPmPeriodCode({
        pmPeriodCode: state.currentPmPeriod.dictCode
      })
        .then(res => {
          selectEvalutaionModal.evalutaionDatas = res.data
        })
        .catch(err => {})
    }

    /**获取所有时间周期类型 */
    function getPeriodType() {
      selectPeriodTypeByTypeCode()
        .then(res => {
          selectEvalutaionModal.pmPeriodList = res.data.sort((a, b) => a.sort - b.sort)
          if (defaultPmPeriodCode) {
            state.currentPmPeriod = selectEvalutaionModal.pmPeriodList.find(
              item => item.dictCode === defaultPmPeriodCode
            )
          } else {
            state.currentPmPeriod = selectEvalutaionModal.pmPeriodList[0]
          }
        })
        .catch(err => {})
    }

    /**打开考评组弹窗 */
    function openEvalutaionModal() {
      selectEvalutaionModal.visible = true
    }

    /**全选 */
    function selectAll() {
      state.beSelectedPmGroupIds = selectEvalutaionModal.evalutaionDatas.map(item => item.pmGroupId)
    }

    /**反选 */
    function selectInvert() {
      let oldEvalutaions = deepClone(state.beSelectedPmGroupIds) as number[]
      let newEvalutaions = selectEvalutaionModal.evalutaionDatas
        .filter(item => oldEvalutaions.indexOf(item.pmGroupId) === -1)
        .map(item => item.pmGroupId)
      state.beSelectedPmGroupIds = newEvalutaions
    }

    /**已选择考评组的标签，点击删除按钮时 */
    function handleTagCloseClick(index: number) {
      state.beSelectedPmGroupIds.splice(index, 1)
    }

    /**发起考核按钮点击 */
    function handleStartPmFormClick() {
      const userDDId = getSession('userDDId')
      if (!userDDId) return
      if (!state.beSelectedPmGroupIds.length) {
        message.warning({
          content: '请选择考评组'
        })
        return
      }
      if (!state.currentPmPeriod) {
        message.warning({
          content: '请选择时间周期'
        })
        return
      }

      let year: string | undefined = undefined

      let dateCount: string | undefined = undefined

      if (state.timePeriod === undefined) {
        message.warning({
          content: '请选择时间周期'
        })
        return
      }

      // 当时间周期为自定义时

      // 当时间周期不是自定义时

      if (typeof state.timePeriod === 'number') {
        dateCount = state.timePeriod + ''
      } else {
        year = state.timePeriod.format('YYYY')

        switch (state.currentPmPeriod.dictCode) {
          case '0025':
            dateCount = state.timePeriod.format('M')
            break
          case '0026':
            switch (state.timePeriod.format('M')) {
              case '0':
                dateCount = '1'
                break
              case '3':
                dateCount = '2'
                break
              case '6':
                dateCount = '3'
                break
              case '9':
                dateCount = '4'
                break
              default:
                dateCount = '1'
                break
            }
            break
          case '0028':
            dateCount = '1'
            break
          case '0029':
            dateCount = undefined
            break
          default:
            dateCount = state.timePeriod.format('M')
            break
        }
      }

      console.log({
        pmGroupIds: state.beSelectedPmGroupIds,
        datePeriodTypeCode: state.currentPmPeriod.dictCode,
        pmFormName: pmFormName.value,
        startUserDDId: userDDId,
        dateCount: dateCount,
        dateYear: year
      })
      startPmForm({
        pmGroupIds: state.beSelectedPmGroupIds,
        datePeriodTypeCode: state.currentPmPeriod.dictCode,
        pmFormName: state.pmFormName || '',
        startUserDDId: userDDId,
        dateCount: dateCount,
        dateYear: year
      })
        .then(res => {
          setTimeout(() => {
            router.back()
          })
        })
        .catch(err => {})
    }

    onMounted(() => {
      getPeriodType()
    })

    return () => (
      <PMLayout>
        <PMNav title='发起考核'></PMNav>
        <PMContent>
          <CCard title='发起考核' showTitle={false} class='pl-24'>
            <table class='table-auto' cellpadding='10px'>
              <tbody>
                <tr>
                  <td class='text-left w-144'>
                    <CnMediumSpan class='text-16'>基本信息</CnMediumSpan>
                  </td>
                  <td></td>
                </tr>
                <tr>
                  <td class='flex items-end justify-end'>
                    <CnMediumSpan>参与考评组：</CnMediumSpan>
                  </td>
                  <td class=''>
                    <a-button class='rounded-4' size='small' onClick={openEvalutaionModal}>
                      选择考评组
                    </a-button>
                    {beSelectedEvalutaions.value.length ? (
                      <div class='mt-12 flex items-center flex-wrap gap-x-8 gap-y-12'>
                        {beSelectedEvalutaions.value.map((item, index) => (
                          <a-tag
                            color='blue'
                            closable
                            onClose={() => {
                              handleTagCloseClick(index)
                            }}
                          >
                            {item.pmGroupName}
                          </a-tag>
                        ))}
                      </div>
                    ) : null}
                  </td>
                </tr>

                {state.currentPmPeriod ? (
                  <tr>
                    <td class='text-right mr-16'>
                      <CnMediumSpan>时间周期：</CnMediumSpan>
                    </td>
                    <td class=''>
                      {state.currentPmPeriod?.dictCode === '0025' ? (
                        <a-date-picker v-model={[state.timePeriod, 'value']} picker='month' />
                      ) : state.currentPmPeriod?.dictCode === '0026' ? (
                        <a-date-picker v-model={[state.timePeriod, 'value']} picker='quarter' />
                      ) : state.currentPmPeriod?.dictCode === '0027' ? (
                        <a-select
                          class='w-122'
                          v-model={[state.timePeriod, 'value']}
                          placeholder='选择半年度'
                        >
                          <a-select-option value={1}>上半年</a-select-option>
                          <a-select-option value={2}>下半年</a-select-option>
                        </a-select>
                      ) : state.currentPmPeriod?.dictCode === '0028' ||
                        state.currentPmPeriod?.dictCode === '0029' ? (
                        <a-date-picker v-model={[state.timePeriod, 'value']} picker='year' />
                      ) : (
                        <a-date-picker v-model={[state.timePeriod, 'value']} picker='month' />
                      )}
                    </td>
                  </tr>
                ) : null}

                {pmFormName.value !== undefined && beSelectedEvalutaions.value.length > 0 ? (
                  <tr>
                    <td class='text-right w-144'>绩效考核名称：</td>
                    <td>
                      <a-input
                        class='w-300'
                        v-model={[state.pmFormName, 'value']}
                        disabled={state.currentPmPeriod?.dictCode !== '0029'}
                      ></a-input>
                    </td>
                  </tr>
                ) : null}

                <tr>
                  <td></td>
                  <td>
                    <a-button
                      class='rounded-4 bg-primary text-white'
                      type='primary'
                      onClick={() => handleStartPmFormClick()}
                    >
                      发起考核
                    </a-button>
                  </td>
                </tr>
              </tbody>
            </table>
          </CCard>
        </PMContent>

        <a-modal
          v-model={[selectEvalutaionModal.visible, 'visible']}
          title='考评组筛选'
          onOk={() => {
            selectEvalutaionModal.visible = false
          }}
        >
          <a-checkbox-group
            class='w-full p-24'
            name='beSelectedEvalutaion'
            v-model={[state.beSelectedPmGroupIds, 'value']}
          >
            <div class='mb-12'>
              <div class='my-12 flex items-center gap-x-12'>
                {selectEvalutaionModal.pmPeriodList.map(item => (
                  <CnMediumSpan
                    class={[
                      'h-34 flex items-center justify-center py-4 px-12 rounded-full cursor-pointer',
                      state.currentPmPeriod?.dictCode === item.dictCode
                        ? 'bg-primary text-white'
                        : ''
                    ]}
                    onClick={() => {
                      state.currentPmPeriod = item
                    }}
                  >
                    {item.dictName}
                  </CnMediumSpan>
                ))}
              </div>
              <a-input
                class='rounded-4'
                v-slots={{
                  prefix: () => <i class='iconfont icon-fangdajing text-info text-14'></i>
                }}
                placeholder='输入考评组名称筛选'
                v-model={[selectEvalutaionModal.pmGroupName, 'value']}
              ></a-input>
            </div>
            <div>
              <div class='flex items-center gap-x-12 mb-12'>
                <a-button class='rounded-4' size='small' onClick={selectAll}>
                  全部
                </a-button>
                <a-button class='rounded-4' size='small' onClick={selectInvert}>
                  反选
                </a-button>
              </div>
              <div class='w-full h-400 flex flex-col gap-y-12 overflow-y-auto'>
                {filterEvalutaionDatas.value.map(item => (
                  <a-checkbox class='m-0' value={item.pmGroupId}>
                    {item.pmGroupName}
                  </a-checkbox>
                ))}
              </div>
            </div>
          </a-checkbox-group>
        </a-modal>
      </PMLayout>
    )
  }
})
